package com.nbb.aop;

import com.alibaba.fastjson.JSONObject;
import com.nbb.common.constant.IConstants;
import com.nbb.common.util.MatchUtil;
import common.util.MD5Util;
import common.util.web.AjaxUtils;
import common.util.web.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;


/**
 * Created by WangXin on 2016/12/13.
 */
public class LoginFilter implements Filter {
    private static final Logger log = Logger.getLogger(LoginFilter.class);

    private String loginUrl = "/pc/index/login";

    /**
     * 免检查地址
     */
    private String uncheckUrls;


    public void init(FilterConfig config) throws ServletException {
        this.uncheckUrls = config.getInitParameter("uncheckUrls");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 判断该请求是否需要拦截
        boolean isCheck = isCheckUrl(request);
        if (!isCheck) {
            chain.doFilter(request, response);
            return;
        }

        // 判断用户登录状态
        boolean loginFlag = isLoginStatus(request);
        //判断用户登录规则
        boolean ruleFlag = isRuleStatus(request);
        String url = request.getRequestURI().replace(request.getContextPath(),
                "");
        if(loginFlag && ruleFlag) {
            // 正常登录状态
            initSessionData(request);// 初始化sessionData
            chain.doFilter(request, response);
        }else if(url.equals(loginUrl)){
            chain.doFilter(request, response);
        }else {
            // 登录状态失效
            if (isAjaxRequest(request)) {
                // 如果为ajax请求则先返回提示信息在跳转页面
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", IConstants.ResponseDefine.Code.ERROR_401.getIndex());
                jsonObject.put("msg","未登陆，请进行登陆");
                AjaxUtils.write(response, jsonObject.toJSONString());
                log.debug(request.getRequestURI()
                        + " ajax request is intercepted ,return "
                        + jsonObject.toJSONString());
            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code",IConstants.ResponseDefine.Code.ERROR_401.getIndex());
                jsonObject.put("msg","未登陆，请进行登陆");
                AjaxUtils.write(response, jsonObject.toJSONString());
            }
        }
    }

    /**
     * 判断当前的登录状态
	 *
     */
    private boolean isLoginStatus(HttpServletRequest request) {
        Cookie cookie = getUCookie(request);
        if (cookie == null) {
            return false;
        }else{
            return true;
        }

    }

    /**
     * 判断当前的登录规则
     * @param request
     * @return
     */
    private boolean isRuleStatus(HttpServletRequest request){
        Cookie u_cookie = getUCookie(request);
        if(u_cookie == null){
            return false;
        }
        Cookie r_cookie = CookieUtil.getCookieByName(request, IConstants.COOKIE_R);
        if(r_cookie == null){
            return false;
        }
        if(StringUtils.isBlank(r_cookie.getValue())){
            return false;
        }
        String ruleStr= MD5Util.string2MD5(u_cookie.getValue()+IConstants.LOGIN_PRIVATE_KEY);
        if(!r_cookie.getValue().equals(ruleStr)){
            return false;
        }
        return true;
    }

    private Cookie getUCookie(HttpServletRequest request) {
        return CookieUtil.getCookieByName(request, IConstants.COOKIE_U);
    }


    /**
     * 判断request是否为ajax请求
     *
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        return requestType != null && requestType.equals("XMLHttpRequest");
    }

    /**
     * 判断请求地址是否要经过拦截
     */
    private boolean isCheckUrl(HttpServletRequest request) {
        String url = request.getRequestURI().replace(request.getContextPath(),
                "");
        String[] uncheckUrlArray = uncheckUrls.split(",");
        if (MatchUtil.simpleMatch(Arrays.asList(uncheckUrlArray), url)) {
            log.debug(url + " is not checked");
            return false;
        } else {
            log.debug(url + " is checked");
            return true;
        }
    }


    /**
     * 初始化sessionData
     *
     */
    private void initSessionData(HttpServletRequest request) {
        request.setAttribute("user","");
    }

    public void destroy() {
    }


}
